package cs.android.view;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.widget.ImageView;
import cs.android.http.HttpClientImpl;

public class ImageViewBitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {
	private final String url;
	private final ImageView imageView;

	public ImageViewBitmapDownloaderTask(ImageView imageView, String url) {
		this.imageView = imageView;
		this.url = url;
	}

	@Override protected Bitmap doInBackground(String... params) {
		return downloadBitmap(url);
	}

	@Override protected void onPostExecute(Bitmap bitmap) {
		imageView.setImageBitmap(bitmap);
	}

	private Bitmap downloadBitmap(String url) {
		HttpClientImpl client = new HttpClientImpl(url);
		return client.getResponseBitmap();
	}

	class FlushedInputStream extends FilterInputStream {
		public FlushedInputStream(InputStream inputStream) {
			super(inputStream);
		}

		@Override public long skip(long n) throws IOException {
			long totalBytesSkipped = 0L;
			while (totalBytesSkipped < n) {
				long bytesSkipped = in.skip(n - totalBytesSkipped);
				if (bytesSkipped == 0L) {
					int oneByte = read();
					if (oneByte < 0) break;
					bytesSkipped = 1;
				}
				totalBytesSkipped += bytesSkipped;
			}
			return totalBytesSkipped;
		}
	}
}